package com.jy.user.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.jy.redis.service.RedisService;
import com.jy.user.entity.User;
import com.jy.user.service.UserService;

@Controller
@RequestMapping(value = "/user")
public class UserController {
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private RedisService redisService;

	@RequestMapping("/findAll")
	@ResponseBody
	public List<HashMap<String, Object>> findAll(HttpServletRequest request,HttpServletResponse response, ModelMap modelMap) throws IOException {
		List<HashMap<String, Object>> data = userService.findAll();
		return data;
	}
	
	@RequestMapping("/testHessianRedis")
	@ResponseBody
	public String testHessianRedis(HttpServletRequest request,HttpServletResponse response, ModelMap modelMap) {
		redisService.set("namekey", "王三锤");
		String name = redisService.get("namekey");
		redisService.del("namekey");
		System.out.println(name);
		return name;
	}
	
	//用户登录
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(User user, HttpServletRequest request) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());
        try{
            subject.login(token);//会跳到我们自定义的realm中
            request.getSession().setAttribute("user", user);
            return "success";
        }catch(Exception e){
            e.printStackTrace();
            request.getSession().setAttribute("user", user);
            request.setAttribute("error", "用户名或密码错误！");
            return "login";
        }
    }

    @RequestMapping("/logout")
    public String logout(HttpServletRequest request) {
        request.getSession().invalidate();
        return "index";
    }   
	
}
